<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Controller\Test;

use App\Constant\TalkEventConstant;
use App\Controller\AbstractController;
use App\Event\TalkEvent;
use App\Services\SocketClientService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

#[Controller(prefix: '/test')]
class SendController extends AbstractController
{
    #[Inject]
    protected SocketClientService $clientService;

    #[RequestMapping(path: 'send', methods: 'post')]
    public function send(RequestInterface $request, ResponseInterface $response)
    {
        $params = $request->all();
        $fds[] = $this->clientService->findUserFds((int) $params['from_user_id']);
        $fds[] = $this->clientService->findUserFds((int) $params['to_user_id']);
        $message = [
            'sender_id' => $params['from_user_id'],
            'receiver_id' => $params['to_user_id'],
            'talk_type' => $params['talk_type'],
            'record_id' => rand(10, 99),
        ];
        $server = server();
        foreach ($fds as $fd) {
            foreach ($fd as $value) {
                if ($server->exist(intval($value))) {
                    $server->push(intval($value), json_encode($message));
                } else {
                    logInfo('send_error', $value . '不存在');
                    $server->close(intval($value));
                }
            }
        }

        // event()->dispatch(new TalkEvent(TalkEventConstant::EVENT_TALK, [
        //     'sender_id'   => $params['from_user_id'],
        //     'receiver_id' => $params['to_user_id'],
        //     'talk_type'   => $params['talk_type'],
        //     'record_id'   => rand(10,99)
        // ]));
    }
}
